<template>
<Card style="height:900px">
  <Form ref="form" :model="form" :rules="rules" :label-width="300">

    <FormItem label="版本ID" prop="id">
      <Input v-model="form.id" :disabled="type==1 || type==2 || type==3 || type==4" style="width: 150px">
        </Input>
    </FormItem>
    <FormItem label="生效时间（起）" prop="startTakeeffectTime">
      <Date-picker type="datetime" :disabled="type==3 || type==4" :value="startTakeeffectTime" v-model="form.startTakeeffectTime" :options="pickerBeginDateBefore" format="yyyy-MM-dd hh:mm:ss" @on-change="changeTime">
      </Date-picker>
    </FormItem>
    <FormItem label="生效时间（止）" prop="endTakeeffectTime" style="">
      <Date-picker type="datetime" :disabled="type==3 || type==4" :value="endTakeeffectTime" v-model="form.endTakeeffectTime" :options="pickerBeginDateAfter" format="yyyy-MM-dd hh:mm:ss">
      </Date-picker>
    </FormItem>
    <!-- <FormItem label="参数明细ID" v-if="type==1"   prop="facesigId" style="">
               <Input v-model="form.facesigId"  :disabled="type==4"  placeholder="" style="width: 185px">
                </Input>
            </FormItem>     -->
    <FormItem label="面签人员数量（人）" v-if="type==2 || type==1 || type==4||type === 3" prop="facesigNumber" style="">
      <Input v-model="form.facesigNumber" :disabled="type==4||type === 3" placeholder="" style="width: 185px" @on-blur="changefacesigNumber()">
        </Input>
    </FormItem>
    <FormItem label="面签时间（分钟）" v-if="type==2 || type==1 || type==3 || type==4" prop="facesigTime" style="">
      <Input v-model="form.facesigTime" :disabled="type==4" @on-blur="changefacesigTime()" style="width: 185px">
        </Input>
    </FormItem>

    <!-- //readonly  -->
    <FormItem v-if="type==2 || type==3 || type == 4">
      <Form ref="formDynamic" :model="formDynamic">
        <FormItem v-for="(item, index) in formDynamic.items" v-if="item.status" :key="index" :label="'预约时间（起）~（止）' + item.index" :prop="'items.' + index + '.startTime'" :rules="{required: true,message: '参数明细[' + item.index +']不能为空'}">
          <Row>
            <i-col span="5">
              <TimePicker :disabled="type==4||(type === 3 && item.show)" :editable='false' @on-change="changeStartVaule(index)" :value="startTime" v-model="item.startTime" confirm placeholder="预约时间（起）" format="HH:mm:ss" hide-disabled-options></TimePicker>
            </i-col>
            <i-col span="5">
              <TimePicker :disabled="type==4||(type === 3 && item.show)" :editable='false' @on-change="changeEndVaule(index)" :value="endTime" v-model="item.endTime" confirm placeholder="预约时间（止）" format="HH:mm:ss" hide-disabled-options :disabled-hours="enabledEndHourDate(item)" :disabled-minutes="enabledEndMinuteDate(item)"></TimePicker>
            </i-col>
            <i-col span="5">
              <i-input :disabled="type==4||(type === 3 && item.show)" type="text" @on-change="changeVaule(index)" :value.sync="item.value" v-model="item.facesigCount" placeholder="面签人数" style="width: 150px"></i-input>
            </i-col>
            <i-col span="4" offset="1" v-if="type===2 || type===1||(type === 3 && !item.show)">
              <Button type="default" @click="handleRemove(index)">删除</Button>
            </i-col>
          </Row>

        </FormItem>
        <FormItem v-if="type==2 || type==1 ||type === 3">
          <Row>
            <Col span="5">
            <Button type="dashed" long @click="handleAdd" icon="plus-round">添加</Button>
            </Col>
          </Row>
        </FormItem>
        <!-- <FormItem>
                  <<Button type="primary" @click="handleSubmit('formDynamic')">Submit</Button>
                    <Button type="ghost" @click="handleReset('formDynamic')" style="margin-left: 8px">重置</Button>
                </FormItem> -->
      </Form>

    </FormItem>
    <FormItem v-if="type==2 || type==3 || type==4">
      <Button type="primary" v-if="type==2 || type==3 " @click="handleSubmit()">确定</Button>
      <Button type="default" style="margin-left: 8px" @click="handleGoBack">返回</Button>
    </FormItem>
    <FormItem v-if="type==1">
      <Button type="primary" @click="handleSubmit()">确定</Button>
      <Button type="default" style="margin-left: 8px" @click="handleGoBack">返回</Button>
    </FormItem>
  </Form>
</Card>
</template>

<script>
export default {
  data () {
    return {
      baseUrl: this.$appContext.marvels_core_approve,
      $ajax: null,
      overallHour: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
      overalMinute: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
      form: {
        timeConfHistoryId: null,
        startTime: null,
        endTime: null,
        startTakeeffectTime: null,
        endTakeeffectTime: null,
        facesigNumber: null,
        facesigCount: null,
        facesigTime: null,
        id: null,
        facesigId: null
      },
      formDynamic: {
        items: [{
          value: '',
          index: 1,
          status: 1
        }]
      },
      rules: {
        // 生效时间 起
        startTakeeffectTime: [{
          type: 'date',
          required: true,
          message: '生效时间（起）不能为空',
          trigger: 'change'
        }],
        endTakeeffectTime: [{
          type: 'date',
          required: true,
          message: '生效时间（止）不能为空',
          trigger: 'change'
        }],
        // 面签时间
        facesigTime: [{
          type: 'string',
          required: true,
          message: '面签时间不能为空',
          trigger: 'blur'
        },
        {
          pattern: this.$util.regExpNum,
          message: '面签时间不能为非数字',
          trigger: 'blur'
        }
        ],
        // 预约时间起
        startTime: [{
          type: 'date',
          required: true,
          message: '预约时间（起）不能为空',
          trigger: 'blur'
        }],
        // 预约时间止
        endTime: [{
          type: 'date',
          required: true,
          message: '预约时间（止）不能为空',
          trigger: 'blur'
        }],
        // 面签人数
        facesigNumber: [{
          pattern: this.$util.regExpNum,
          message: '面签人数不能为非数字',
          trigger: 'blur'
        }]
      },
      pickerBeginDateBefore: {
        disabledDate: (time) => {
          let endDateVal = this.form.endTakeeffectTime
          if (endDateVal) {
            return time.getTime() > endDateVal
          }
        }
      },
      pickerBeginDateAfter: {
        disabledDate: (time) => {
          let beginDateVal = this.form.startTakeeffectTime
          if (beginDateVal) {
            return time.getTime() < beginDateVal
          }
        }
      },
      copyFacesig: {},
      index: 1,
      items: [],
      timeConfHistoryId: null,
      startTime: null,
      endTime: null,
      startTakeeffectTime: null,
      endTakeeffectTime: null,
      facesigNumber: null,
      facesigCount: null,
      facesigTime: null,
      id: null,
      facesigId: null
    }
  },
  methods: {
    changeTime: function (date) {
      this.form.endTakeeffectTime = ''
      this.pickerBeginDateAfter = {
        disabledDate (time) { // 开始时间-结束时间
          return (time.getTime() < new Date(date).getTime())
        }
      }
    },
    changeStartVaule: function (index) {
      var date = this.formDynamic.items[index].startTime
      var arry = date.split(':')
      if (this.form.facesigTime && parseInt(this.form.facesigTime) > 0) {
        var endMinutes = parseInt(arry[1]) + parseInt(this.form.facesigTime)
        var a = parseInt(endMinutes / 60)
        var b = endMinutes % 60
        var c = parseInt(arry[0]) + parseInt(a)
        if (c > 23) b = 59
        if (c > 23) c = 23
        this.formDynamic.items[index].endTime = c + ':' + b + ':' + arry[2]
      } else {
        this.formDynamic.items[index].endTime = ''
      }
    },
    changeEndVaule: function (index) {
      var date = this.formDynamic.items[index].endTime
      var startDate = this.formDynamic.items[index].startTime
      if (!startDate) return
      var arry = date.split(':')
      var startDateAry = startDate.split(':')
      var minutes = startDateAry[1]
      var hour = startDateAry[0]
      if (arry[1] < minutes) {
        this.formDynamic.items[index].endTime = arry[0] + ':' + minutes + ':' + arry[2]
      }
      if (arry[0] < hour) {
        if (arry[1] < minutes) {
          this.formDynamic.items[index].endTime = hour + ':' + minutes + ':' + arry[2]
        } else {
          this.formDynamic.items[index].endTime = hour + ':' + arry[1] + ':' + arry[2]
        }
      }
    },
    // 当前可以使用的小时
    // enabledHourDate: function () {
    //   var date = new Date()
    //   var hour = date.getHours() // 时
    //   var hourAry = []
    //   for (var i = 0; i < this.overallHour.length; i++) {
    //     if (this.overallHour[i] < hour) {
    //       hourAry.push(this.overallHour[i])
    //     }
    //   }
    //   return hourAry
    // },
    // 当前可以使用的分钟数
    // enabledMinuteDate: function () {
    //   var date = new Date()
    //   var mnute = date.getMinutes()// 分
    //   var mnuteAry = []
    //   for (var i = 0; i < this.overalMinute.length; i++) {
    //     if (this.overalMinute[i] < mnute) {
    //       mnuteAry.push(this.overalMinute[i])
    //     }
    //   }
    //   return mnuteAry
    // },
    // 当前可以使用的小时(结束)
    enabledEndHourDate: function (item) {
      var hour = '' // 时
      if (item.startTime && item.startTime !== '' && item.startTime !== null) {
        var strAry = item.startTime.split(':')
        hour = strAry[0]
      } else {
        var date = new Date()
        hour = date.getHours()
      }
      var hourAry = []
      for (var i = 0; i < this.overallHour.length; i++) {
        if (this.overallHour[i] < hour) {
          hourAry.push(this.overallHour[i])
        }
      }
      return hourAry
    },
    // 当前可以使用的分钟数(结束)
    enabledEndMinuteDate: function (item) {
      var mnute = '' // 分钟
      if (item.startTime && item.startTime !== '' && item.startTime !== null) {
        var strAry = item.startTime.split(':')
        mnute = strAry[1]
      } else {
        var date = new Date()
        mnute = date.getMinutes() // 分
      }
      var mnuteAry = []
      for (var i = 0; i < this.overalMinute.length; i++) {
        if (this.overalMinute[i] < mnute) {
          mnuteAry.push(this.overalMinute[i])
        }
      }
      return mnuteAry
    },
    handleSubmit () {
      var vm = this
      if (vm.form.facesigNumber && Number(vm.form.facesigNumber) <= 0) {
        this.$Message.warning('面签人员数量为0，该配置无效')
        return
      }
      this.$refs.form.validate(valid => {
        if (this.type === 2 || this.type === 3) {
          this.$refs['formDynamic'].validate(valid1 => {
            if (valid1 && valid) {
              var config = {
                title: '提示'
              }
              if (this.type === 1) {
                config.content = '是否确认修改?'
                config.onOk = vm.updateFaceSigAppointment
              } else if (this.type === 2) {
                config.content = '是否确认新建?'
                config.onOk = vm.addFaceSigAppointment
              } else if (this.type === 3) {
                config.content = '是否确认新增?'
                config.onOk = vm.addFaceSigAppointment
              }
              vm.$Modal.confirm(config)
            }
          })
        } else {
          if (valid) {
            var config = {
              title: '提示'
            }
            if (this.type === 1) {
              config.content = '是否确认修改?'
              config.onOk = vm.updateFaceSigAppointment
            } else if (this.type === 2) {
              config.content = '是否确认新建?'
              config.onOk = vm.addFaceSigAppointment
            } else if (this.type === 3) {
              config.content = '是否确认新增?'
              config.onOk = vm.addFaceSigAppointment
            }
            vm.$Modal.confirm(config)
          }
        }
      })
    },
    // 重置输入框
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    // 新增输入框预约时间（起止，面签人数）
    handleAdd () {
      if (this.formDynamic.items.length < 1) {
        this.index = 0
      }
      this.index++
      this.formDynamic.items.push({
        value: '',
        index: this.index,
        status: 1
      })
    },
    // 删除输入框
    handleRemove (index) {
      if (this.formDynamic.items.length === 1) {
        this.$Message.warning('至少要有一条预约时间明细')
        return
      }
      this.formDynamic.items.splice(index, 1)
      if (this.formDynamic.items.length > 0) {
        for (var i = 0; i < this.formDynamic.items.length; i++) {
          this.formDynamic.items[i].index = i + 1
        }
      }
    },
    addFaceSigAppointment: function () {
      this.setDefaultEndTime(true)
      var paramsData = this.formDynamic.items
      var vm = this
      // 如果是新增只增加明细
      if (vm.type === 3) {
        var faceSigConfigurationList1 = []
        var items = this.formDynamic.items
        items.forEach(element => {
          if (!element.show) {
            if (!element.facesigCount || element.facesigCount === null || element.facesigCount === '' || element.facesigCount === 0) {
              if (vm.form.facesigNumber !== null && vm.form.facesigNumber !== '' && Number(vm.form.facesigNumber) !== 0) {
                element.facesigCount = vm.form.facesigNumber
              }
            }
            faceSigConfigurationList1.push(element)
          }
        })
        var Data = {
          'id': this.form.id,
          'faceSigConfigurationList': faceSigConfigurationList1
        }
        this.$ajax.post(this.baseUrl + 'approve/mqcspz/service/addFaceSigAppointment', Data).then(re => {
          var data = re.data
          var code = data.code
          var message = data.message
          if (code !== 'success') {
            this.$Message.warning(message)
            return
          } else {
            this.$Message.success(message)
          }
          this.handleGoBack()
        }).catch(er => {})
      } else {
        var params = this.form
        var paramsList = []
        for (var i = 0; i < paramsData.length; i++) { // 添加进参数明细
          var faceSigConfigurationList = {}
          faceSigConfigurationList.startTime = paramsData[i].startTime
          faceSigConfigurationList.endTime = paramsData[i].endTime
          faceSigConfigurationList.facesigTime = params.facesigTime
          faceSigConfigurationList.facesigCount = paramsData[i].facesigCount
          faceSigConfigurationList.facesigNumber = params.facesigNumber
          if (faceSigConfigurationList.startTime !== null && faceSigConfigurationList.startTime !== '' && faceSigConfigurationList.endTime !== '' && faceSigConfigurationList.endTime !== null) {
            paramsList.push(faceSigConfigurationList)
          }
        }
        var paramsAll = {
          'startTakeeffectTime': params.startTakeeffectTime,
          'endTakeeffectTime': params.endTakeeffectTime,
          'faceSigConfigurationList': paramsList,
          'facesigTime': this.form.facesigTime
        }
        this.$ajax.post(this.baseUrl + 'approve/mqcspz/service/addTimeConfHistory', paramsAll).then(re => {
          var data = re.data
          var code = data.code
          var message = data.message
          if (code !== 'success' && data === 0) {
            this.$Message.warning(message)
            return
          }
          this.handleGoBack()
        }).catch(er => {})
      }
    },
    // 返回
    handleGoBack: function () {
      this.$router.push({
        name: 'facesigTimeParameter'
      })
    },
    // 编辑
    updateFaceSigAppointment: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          var params = this.form
          var paramsAll = {}
          var faceSigConfigurationDTO = {}
          paramsAll.id = params.id // 添加进参数明细
          faceSigConfigurationDTO.facesigId = this.$route.query.facesigId
          faceSigConfigurationDTO.facesigTime = params.facesigTime
          faceSigConfigurationDTO.facesigNumber = params.facesigNumber
          faceSigConfigurationDTO.timeConfHistoryId = params.id
          paramsAll.faceSigConfigurationDTO = faceSigConfigurationDTO
          this.$ajax.post(this.baseUrl + 'approve/mqcspz/service/updateFaceSigAppointment', paramsAll).then(re => {
            var data = re.data
            var code = data.code
            var message = data.message
            if (code !== 'success') {
              this.$Message.warning(message)
              return
            } else {
              this.$Message.success('更新成功')
            }
            this.handleGoBack()
          }).catch(er => {

          })
        }
      })
    },
    // 初始化页面数据
    initpage: function () {
      // 编辑
      var query = this.$route.query
      if (this.type === 1) {
        this.form.id = query.id
        this.form.facesigId = query.facesigId
        this.getByDatail()
        // 新增
      } else if (this.type === 3) {
        this.form.id = query.id
        this.form.facesigId = query.facesigId
        this.getByDatail()
        // 查看
      } else if (this.type === 4) {
        this.form.id = query.id
        this.form.facesigId = query.facesigId
        this.getByDatail()
      }
    },
    // 通过ID获取详情
    getByDatail: function () {
      // 如果是新建
      var vm = this
      var params = {
        id: this.form.id,
        faceSigConfigurationDTO: {
          facesigId: this.form.facesigId
        }
      } //, facesigId: this.form.facesigId
      this.$ajax.post(this.baseUrl + 'approve/mqcspz/service/getById', params).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success' && data === 0) {
          this.$Message.warning(message)
          return
        }

        vm.form = data.data
        vm.form.startTakeeffectTime = vm.$util.formatTime(vm.form.startTakeeffectTime)
        vm.form.endTakeeffectTime = vm.$util.formatTime(vm.form.endTakeeffectTime)

        // this.formDynamic.items[0].startTime,
        // 时间
        if (vm.type !== 2) {
          if (vm.type === 3 || vm.type === 4) {
            vm.formDynamic.items = []
            for (var i = 0; i < vm.form.faceSigConfigurationList.length; i++) {
              // if (vm.form.faceSigConfigurationList[i].facesigId === vm.$route.query.facesigId) {
              vm.form.facesigId = vm.form.faceSigConfigurationList[0].facesigId
              vm.form.facesigNumber = vm.form.faceSigConfigurationList[0].facesigNumber
              vm.form.facesigTime = vm.form.faceSigConfigurationList[0].facesigTime + ''
              vm.formDynamic.items.push({
                startTime: vm.form.faceSigConfigurationList[i].startTime,
                endTime: vm.form.faceSigConfigurationList[i].endTime,
                facesigCount: vm.form.faceSigConfigurationList[i].facesigCount,
                show: true,
                value: '',
                index: (i + 1),
                status: 1
              })
              // }
            }
            this.index = vm.form.faceSigConfigurationList.length
          } else {
            for (var j = 0; j < vm.form.faceSigConfigurationList.length; j++) {
              if (vm.form.faceSigConfigurationList[i].facesigId === vm.$route.query.facesigId) {
                vm.form.facesigId = vm.form.faceSigConfigurationList[i].facesigId
                vm.form.facesigNumber = vm.form.faceSigConfigurationList[i].facesigNumber
                vm.form.facesigTime = vm.form.faceSigConfigurationList[i].facesigTime + ''
                vm.formDynamic.items[0].startTime = vm.form.faceSigConfigurationList[i].startTime
                vm.formDynamic.items[0].endTime = vm.form.faceSigConfigurationList[i].endTime
                vm.formDynamic.items[0].facesigCount = vm.form.faceSigConfigurationList[i].facesigCount
              }
            }
          }
        }
        vm.copyFacesig = JSON.parse(JSON.stringify(vm.form))
      }).catch(er => {

      })
    },
    changeVaule: function (index) {
      // 面签人数不能超过面签人员数量
      var data = this.formDynamic.items
      if (!this.form.facesigNumber || this.form.facesigNumber === null || this.form.facesigNumber === '') return
      var facesigNumber = Number(this.form.facesigNumber)
      if (Number(data[index].facesigCount) > facesigNumber) {
        data[index].facesigCount = facesigNumber
      }
    },
    changefacesigTime: function () {
      // 根据起输入的时间及设定的面签时间自动计算回填预约时间（止）
      this.setDefaultEndTime(false)
    },
    setDefaultEndTime (isDefault) {
      var stime, h, hh, m, mm, sstime
      var data = this.formDynamic.items
      if (data && data.length > 0) {
        data.forEach(item => {
          if (!item.startTime) {
            return
          }
          stime = item.startTime.split(':')
          for (var i = 0; i < stime.length; i++) {
            h = stime[0]
            m = stime[1]
          }
          mm = Number(m)
          hh = Number(h)
          sstime = Number(this.form.facesigTime)
          var c = parseInt((mm + sstime) / 60)
          var d = (mm + sstime) % 60
          hh = hh + c
          if (hh > 23) d = 59
          if (hh > 23) hh = 23
          var endtime
          if (hh < 10) {
            endtime = '0' + hh + ':' + d + ':' + '00'
          } else {
            endtime = hh + ':' + d + ':' + '00'
          }
          if (isDefault) {
            if (!item.endTime || item.endTime === null || item.endTime === '') {
              item.endTime = endtime
            }
          } else {
            item.endTime = endtime
          }
        })
      }
    },
    // 改变面签人数
    changefacesigNumber: function () {
      var data = this.formDynamic.items
      var facesigNumber = Number(this.form.facesigNumber)
      if (data.length > 0) {
        data.forEach(item => {
          if (Number(item.facesigCount) > facesigNumber) {
            item.facesigCount = facesigNumber
          }
        })
      }
    }
  },
  computed: {
    type () { // 1 编辑  2 新建  3 新增  4 查看
      return parseInt(this.$route.query.type)
    }
  },
  created () {
    this.$ajax = this.$util.ajax()
    this.initpage()
    if (this.type === '2') {
      var date = new Date()
      this.form.startTakeeffectTime = this.$util.formatTime(date.getTime())
    }
  }
}
</script>
<style>
